package handlers

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"zy1/models"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名和密码不能为空",
		})
		return
	}
	var user models.User
	models.DB.Where("username=?", username).First(&user)
	if user.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != password {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
}
func StoreAdd(c *gin.Context) {
	name := c.PostForm("name")
	address := c.PostForm("address")
	area := c.PostForm("area")
	store := models.Store{
		Model:   gorm.Model{},
		Name:    name,
		Address: address,
		Area:    area,
	}
	err := models.DB.Create(&store).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "添加成功",
			"data": store,
		})
		return
	}
}
func StoreList(c *gin.Context) {
	var stores []models.Store
	err := models.DB.Find(&stores).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": stores,
		})
		return
	}
}
